<template>
  <div class="activecode">
    <div class="header">
      <table>
        <tr>
          <td>
            <span>服务器：</span>
            <Server ref="ServerChild" :showServer="showServer" />
          </td>
          <td>
            <span>开始时间：</span>
            <el-date-picker
              v-model="first_time"
              type="datetime"
              value-format="timestamp"
              placeholder="选择日期时间"
            >
            </el-date-picker>
          </td>
          <td>
            <span>结束时间：</span>
            <el-date-picker
              v-model="last_time"
              type="datetime"
              value-format="timestamp"
              placeholder="选择日期时间"
            >
            </el-date-picker>
          </td>
          <td>
            <el-button type="primary" @click="search()">查询</el-button>
          </td>
          <td>
            <el-button type="primary" @click="ExportExcel()"
            >导出Excel</el-button>
          </td>
        </tr>
      </table>
    </div>
    <div class="content">
      <el-main v-loading="loading">
        <el-table
          border
          class="table"
          :header-cell-style="{
            color: '#333',
            fontFamily: 'MicrosoftYaHeiUI',
            fontWeight: 500,
            fontSize: '16px',
          }"
          :data="tableData.slice((page_index - 1) * page_size,page_index * page_size)"
        >
          <el-table-column 
            sortable 
            prop="number" 
            label="编号"
          >
          </el-table-column>
          <el-table-column 
            sortable 
            prop="gift_id" 
            label="物品id"
          >
          </el-table-column>
          <el-table-column 
            sortable 
            prop="use_count" 
            label="使用次数"
          >
          </el-table-column>
          <el-table-column
            sortable
            :formatter="formatDate"
            prop="effective_start_time"
            label="生效开始时间"
          >
          </el-table-column>
          <el-table-column
            sortable
            :formatter="formatDate"
            prop="expiration_end_time"
            label="失效结束时间"
          >
          </el-table-column>
          <el-table-column
            header-align="center"
            align="center"
            width="200"
            label="操作"
          >
            <template slot-scope="scope">
              <el-button @click="showUpdate(scope.row)" type="primary">
                <i class="el-icon-edit"></i>修改
              </el-button>
              <el-button @click="del(scope.row)" type="danger">
                <i class="el-icon-delete"></i>删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
        <pageNation
          :total="tableData.length"
          :page-size="page_size"
          @pageChange="pageChange"
          :page_index="page_index"
        />
      </el-main>
      <ActiveCodeDialog
        :dialog="dialog"
        :ActivationCodeForm="ActivationCodeForm"
        @update="getProfile($event)"
      />
    </div>
  </div>
</template>
<script>
import xlsx from "../../../public/js/xlsx.full.min.js";
import FileSaver from "../../../public/js/FileSaver";
import Server from "../../components/server/Server.vue";
import pageNation from "../../components/pagenation/pageNation";
import ActiveCodeDialog from "../../components/activecode/ActiveCodeDialog";
import {formatDate} from '../../utils/index'
export default {
  name: "ActiveCode",
  components: { Server, pageNation, ActiveCodeDialog },
  data() {
    return {
      showServer: true,
      server_id: "",
      first_time: "",
      last_time: "",
      loading: false,
      //时间戳转换格式
      formatDate:formatDate,
      page_index: 1, // 页数
      page_size: 10,
      dialog: {
        show: false, //是否显示弹出框
        title: "", //弹出框的title
        option: "edit",
      },
      ActivationCodeForm: {
        number: "",
        gift_id: "",
        use_count: "",
        effective_start_time: "",
        expiration_end_time: "",
      },
      tableData: [],
    };
  },
  mounted() {
    this.first_time = window.localStorage.getItem("first_time");
    this.last_time = window.localStorage.getItem("last_time");
  },
  methods: {
    //分页
    pageChange(item) {
      this.currentPage = item.page_index;
      this.pageSize = item.page_limit;
    },
    //搜索
    search() {
      var last_time = this.last_time;
      var first_time = this.first_time;
      window.localStorage.setItem("last_time", last_time);
      window.localStorage.setItem("first_time", first_time);
      var server_id = this.$refs.ServerChild.server_id;
    },
    getProfile(acode) {
      console.log(acode);
    },
    //点击删除
    del(row) {
      this.$confirm("确定删除该条信息吗?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).then(() => {
          console.log(row);
      }).catch(() => {
          return;
      });
    },
    //点击修改
    showUpdate(row) {
      this.dialog = {
        show: true, //是否显示弹出框
        title: "修改激活码", //弹出框的title
        option: "edit",
      },
      this.ActivationCodeForm = {
        number: row.number,
        gift_id: row.gift_id,
        use_count: row.use_count,
        effective_start_time: row.effective_start_time * 1000,
        expiration_end_time: row.expiration_end_time * 1000,
      };
    },
    //导出excel
    ExportExcel() {
      // 设置当前日期
      let time = new Date();
      let year = time.getFullYear();
      let month = time.getMonth() + 1;
      let day = time.getDate();
      let hour = time.getHours();
      let seconds = time.getSeconds();
      let minutes = time.getMinutes();
      let name =year + "" + month + "" + day + "" + hour + "" + minutes + "" + seconds;
      if (this.tableData.length > 0) {
        //当前页为第一页
        this.page_index = 1;
        //每页大小限制条数：为总条数（将表格数据全部渲染出来在第一页上）
        this.page_size = this.tableData.length;
        var xlsxParam = { raw: true }; //转换成excel时，使用原始的格式
        this.$nextTick(function () {
          var wb = xlsx.utils.table_to_book(
            document.querySelector(".table"),
            xlsxParam
          );
          var wbout = xlsx.write(wb, {
            bookType: "xlsx",
            bookSST: true,
            type: "array",
          });
          try {
            FileSaver.saveAs(
              new Blob([wbout], { type: "application/octet-stream" }),
              name + ".xlsx"
            );
          } catch (e) {
            if (typeof console !== "undefined") console.log(e, wbout);
          }
          this.page_size = 10;
          return wbout;
        });
      } else {
        this.$message({ type: "warning", message: "表中没有数据不能导出" });
        return;
      }
    }
  }
};
</script>
<style scoped>
.activecode {
  width: 100%;
  height: auto;
  background-color: #fff;
}
.activecode td {
  padding: 18px;
  font-size: 14px;
  display: flex;
  float: left;
}
</style>